﻿@page "/login"
@layout NullLayout
@using System.IdentityModel.Tokens.Jwt;
@using AdminShared.Models.Authorize
@attribute [ReuseTabsPage(Ignore = true)]


<body>
    <div style="width: 100vw;height: 100vh;text-align: center;position: relative;background-image: url('img/login.jpg');">

        <div style="position:absolute; left:200px;top:40%;color:#fff">
            <div style=" color: #fff;font-size: 45px;line-height: 60px;width: 100%;font-weight:700">
                Welcome
            </div>
            <div style="font-size: 20px;margin-top: 10px;font-family: ui-monospace;display:flex">
                Hi，你来啦！
            </div>
        </div>

        <div style="min-width: 400px;display: inline-block;background-color: white;border-radius: 10px;position: absolute;right:18%;top:30%; padding: 35px;">
            <h1>管理系统</h1>

            <Form Model="@loginData" OnFinish="LoginAction">

                <FormItem>
                    <Input @bind-Value="@context.UserName" Style="padding: 10px;" Placeholder="用户名" />
                </FormItem>

                <FormItem>
                    <InputPassword @bind-Value="@context.PassWord" Style="padding: 6px;" Placeholder="密码" />
                </FormItem>

                <FormItem Style="margin-top:10px">
                    <Button Type="@ButtonType.Primary" HtmlType="submit" Block Loading="@submitLoading" Style="padding: 10px 0; height: 40px;">
                        登录
                    </Button>
                </FormItem>
            </Form>
        </div>

    </div>
</body>


@code
{
    bool submitLoading = false;


    override protected void OnInitialized()
    {
        var authorization = LocalStorage.GetItemAsString("Authorization");

        if (!string.IsNullOrEmpty(authorization))
        {
            JwtSecurityToken securityToken = new(authorization);

            var expTimeL = Convert.ToInt64(securityToken.Claims.ToList().Where(t => t.Type == "exp").FirstOrDefault()!.Value);

            var expTime = TimeZoneInfo.ConvertTimeToUtc((new DateTime(1970, 1, 1)).ToLocalTime()).ToLocalTime().AddSeconds(expTimeL);

            if (expTime > DateTime.UtcNow)
            {
                NavigationManager.NavigateTo("");
            }
        }
    }


    private DtoLogin loginData = new();

    private async void LoginAction()
    {

        submitLoading = true;

        using (var httpResponse = await Http.PostAsJsonAsync<DtoLogin>("Authorize/GetToken", loginData))
        {
            if ((int)httpResponse.StatusCode == 200)
            {
                var token = httpResponse.Content.ReadAsStringAsync().Result;
                LocalStorage.SetItemAsString("Authorization", token);
                NavigationManager.NavigateTo("");
            }
        }

        submitLoading = false;

        StateHasChanged();

    }

}